/* ticket.c */

#define _XOPEN_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "ticket.h"

ticket_collection_t *ticket_collection_open(const char *path){
	FILE *fp = NULL;
	ticket_collection_t *col;
	ticket_t * tics;
	char buffer[512];
	int count = 0;
	
	if((fp = fopen(path, "r"))== NULL ){
		return NULL;
	}
	
	if(fgets(buffer, 512, fp) == NULL)return NULL;
	
	count = atoi(buffer);
	if(count<=0) return NULL;
	
	if((col = (ticket_collection_t *)malloc(sizeof(ticket_collection_t))) == NULL){
		fclose(fp);
		return NULL;
	}
	col->len = 0;
	strcpy(col->path, path);
	if((tics = (ticket_t *)malloc(sizeof(ticket_t)*count)) == NULL){
		fclose(fp);
		return NULL;
	}
	col->tickets = tics;
	while(fgets(buffer,512, fp) != NULL){
		char *id;
		char *trainno;
		char *time;
		char *num;
		char *des;
		struct tm tim;
		id = buffer;
		if((trainno = strstr(id,"\t")) != NULL){
			printf(".");
			*trainno = '\0';
			trainno += 1;
		}else continue;
		if((time = strstr(trainno,"\t")) != NULL){
			*time = '\0';
			time += 1;
		}else continue;
		if((num = strstr(time,"\t")) != NULL){
			*num = '\0';
			num += 1;
		}else continue;
		if((des = strstr(num,"\t")) != NULL){
			*des = '\0';
			des += 1;
		}else continue;
		des[strlen(des)-1] = '\0';	
		col->tickets[col->len].id = atoi(id);
		strcpy(col->tickets[col->len].trainno,trainno);
		strptime(time,"%Y-%m-%d %H:%M:%S",&tim);
		col->tickets[col->len].time = mktime(&tim);
		col->tickets[col->len].num = atoi(num);
		strcpy(col->tickets[col->len].description,des);
		col->len ++;
		if(col->len >= count)break;	
	}
	
	return col;
}

int ticket_collection_close(ticket_collection_t * tc){
	int i ;
	char time[64];
	struct tm tim;
	FILE *log_file;
	if (tc == NULL) return -1;
	log_file = fopen(tc->path, "w");
	if(log_file == NULL){
		perror("Open log file failed.");
		return -1;
	}
	fprintf(log_file,"%d\n", tc->len);
	// 1	T508	2007-01-12 18:00:00	100	Nanjing->Shanghai
	for(i =0; i<tc->len; i++){
		gmtime_r(&(tc->tickets[i].time), &tim);
		strftime(time, 64,"%Y-%m-%d %H:%M:%S",&tim);

		fprintf(log_file, "%d\t%s\t%s\t%d\t%s\n",
			tc->tickets[i].id,
			tc->tickets[i].trainno,
			time,
			tc->tickets[i].num,
			tc->tickets[i].description
			);
	}
	fclose(log_file);
	//free structs
	free(tc->tickets);
	free(tc);
	return 0;
}
